<?php
namespace app\middleware;

class Cors
{
    public function handle($request, \Closure $next)
    {
        // 允许的域名（生产环境建议替换为实际前端域名）
        $allowOrigin = [
            'http://your-frontend-domain.com',
            'https://your-frontend-domain.com'
        ];
        
        // 获取请求来源
        $origin = $request->header('origin');
        
        // 设置响应头
        $response = $next($request);
        $response->header([
            'Access-Control-Allow-Origin' => in_array($origin, $allowOrigin) ? $origin : '*',
            'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS',
            'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With',
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Max-Age' => '86400' // 预检请求缓存时间(24小时)
        ]);
        
        // 处理 OPTIONS 预检请求
        if ($request->method() == 'OPTIONS') {
            $response->code(204); // 无内容状态码
        }
        
        return $response;
    }
}